package com.chinaunicom.libreoffice.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

@RestController
public class LibreOfficeController {

    // 输入的 Word 文件路径
    private static final String wordFilePath = "/data/libreoffice/word/";
    private static final Logger log = LoggerFactory.getLogger(LibreOfficeController.class);

    private static final String outDir = "/data/libreoffice/pdf/";

    @PostMapping("/convertToPdf")
    public byte[] convert(MultipartFile file) {
        try {
            File wordFile = convertMultipartFileToFile(file);
            // 输出目录（PDF 会生成在此目录下，与输入同名，但扩展名为 .pdf）
            ProcessBuilder pb = new ProcessBuilder(
                    "libreoffice",
                    "--headless",
                    "--convert-to", "pdf",
                    wordFile.getAbsolutePath(),
                    "--outdir", outDir
            );

            // 可选：重定向错误流到标准输出，方便调试
            pb.redirectErrorStream(true);

            // 启动进程
            Process process = pb.start();

            // 等待转换完成
            int exitCode = process.waitFor();
            if (exitCode == 0) {
                // 获取后缀名称
                String fileSuffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                String pdfFileName = Objects.requireNonNull(file.getOriginalFilename()).replace("." + fileSuffix, ".pdf");
                boolean b = wordFile.delete();
                System.err.println("PDF 文件名："+ fileSuffix);

                log.info("✅ Word 转 PDF 成功！原文件已删除:{}", b);
                Path pdfPath = Paths.get(outDir, pdfFileName);
                // 7. 准备返回 PDF 文件给客户端（触发浏览器下载）
                File pdfFile = pdfPath.toFile();
                return fileToBytes(pdfFile, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Word 转 PDF 失败:{}", e.getMessage());
        }
        return null;
    }

    public static File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        // 1. 检查文件是否为空
        if (multipartFile.isEmpty()) {
            throw new IllegalArgumentException("上传的文件为空");
        }
        String fileName = multipartFile.getOriginalFilename();

        // 2. 创建目标 File 对象
        File targetFile = new File(wordFilePath + "/" + fileName);

        // 3. 确保目标目录存在
        File parentDir = targetFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            boolean b = parentDir.mkdirs(); // 创建父目录（如果不存在）
            log.info("创建目录成功：{}", b);
        }
        // 4. 将 MultipartFile 内容写入到目标 File
        multipartFile.transferTo(targetFile);
        // 5. 返回生成的 File 对象
        return targetFile;
    }

    public static byte[] fileToBytes(File file, Boolean delete) {
        byte[] data = null;
        int len;
        byte[] bs = new byte[1024];
        if (file.exists()) {
            try (ByteArrayOutputStream bout = new ByteArrayOutputStream();
                 FileInputStream fs = new FileInputStream(file);) {
                while ((len = fs.read(bs)) != -1) {
                    bout.write(bs, 0, len);
                }
                // 转成byte字节
                data = bout.toByteArray();
            } catch (IOException e) {
                log.error("File to Byte:{}", e.getMessage());
            } finally {
                if (Boolean.TRUE.equals(delete)) {
                    boolean b = file.delete();
                    log.info("{}是否被删除:{}", file.getName(), b);
                }
            }
        }
        return data;
    }

}
